package controller;

import com.fasterxml.jackson.databind.ObjectMapper;
import model.Blog;
import model.BlogDao;
import model.User;
import model.UserDao;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;

@WebServlet("/userInfo")
public class UserInfoServlet extends HttpServlet {
    ObjectMapper objectMapper=new ObjectMapper();
    //查询用户信息
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        String blogId=req.getParameter("blogId");
        HttpSession session=req.getSession(false);
        if (session==null){
            resp.setStatus(403);
            resp.setContentType("text/html;charset=utf8");
            resp.getWriter().write("当前用户状态未登录");
            return;
        }
        User user=new User();
        user= (User) session.getAttribute("user");
        if (user==null){
            resp.setStatus(403);
            resp.setContentType("text/html;charset=utf8");
            resp.getWriter().write("当前用户状态未登录");
            return;
        }
        if (blogId==null){
            System.out.println(user.getNickName());
            user.setPassword("");//保护用户密码
            //说明这是博客列表页发送的请求，返回当前登录用户信息
            resp.setContentType("application/json;charset=utf8");
            String userJson=objectMapper.writeValueAsString(user);
            resp.getWriter().write(userJson);
        }else{
            //说明这是博客详情页发送的请求
            BlogDao blogDao=new BlogDao();
            Blog blog=blogDao.queryBlogById(Integer.parseInt(blogId));
            if (blog==null){
                resp.setStatus(403);
                resp.setContentType("text/html;charset=utf8");
                resp.getWriter().write("当前 blogId 有误!");
                return;
            }
            User author=new User();
            UserDao userDao=new UserDao();
            author=userDao.queryInfoByUserId(blog.getUserId());
            if (author==null){
                resp.setStatus(403);
                resp.setContentType("text/html;charset=utf8");
                resp.getWriter().write("当前博客对应作者信息查询失败！");
                return;
            }
            author.setPassword("");
            //判断当前blog是否为登录用户所写，实现删除blog的判断
            if(user.getUserId()==author.getUserId()){
                author.setIsYourBlog(1);
            }else{
                author.setIsYourBlog(0);
            }
            resp.setContentType("application/json;charset=utf8");
            String authorJson=objectMapper.writeValueAsString(author);
            resp.getWriter().write(authorJson);
        }
    }
}


